<template>
    <div>
        <div class="anniu anniu2" @click="exportTable()">导出</div>
    </div>
</template>

<script setup lang="ts">
import axios from "axios";
import moment from 'moment'
import userMainStore from "~/store/modules/app";
const mainStore = userMainStore();
import domainsFuc from '~/request/domains'
import { onMounted } from "vue";
// props引用，如果是在template中直接取值title,在script中使用props.title
const props = defineProps({
    url: {
        default: '',
        type: String
    },
    Name: {
        default: '',
        type: String
    }
})


const exportTable = () => {
    axios.post(domainsFuc(process.env.NODE_ENV).domain + props.url, { token: mainStore.Authorization }, {
        responseType: 'blob' //必填项，不然生成是乱码
    }).then(res => {
        // console.log("res:", res.data)
        downloadExcel(res.data, props.Name + moment().format('YYYY-MM-DD'))
    })

}

const downloadExcel = (fileDate: any, fileName: string) => {
    // TODO fileDate 的ts类型应该是 Blob，但是我这里接口返回的数据类型是 res: AxiosResponse<any, any>，会导致提示类型不匹配，所以用any吧
    return new Promise((resolve, reject) => {
        // 为 blob 设置文件类型，这里以 .xlsx 为例
        const blob = new Blob([fileDate], {
            type: 'application/vnd.ms-excel',
        })

        // 创建一个临时的url指向blob对象
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = fileName + '.xlsx'
        a.click()

        // 释放这个临时的对象url
        URL.revokeObjectURL(url)

        return resolve('导出成功')
    })
}
onMounted(() => {
})

</script>

<style scoped lang="scss">
.anniu {
    width: 90px;
    height: 34px;
    background: #F8F8F8;
    border: 1px solid #3244DE;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #3244DE;
    cursor: pointer;
    margin-left: 20px;
}

.anniu2 {
    border: 1px solid #264E71;
    color: #264E71;
}
</style>